from flask import request
from wechatpy import parse_message
from wechatpy.exceptions import InvalidSignatureException
from wechatpy.utils import check_signature

from app.message_factory import MessageHandler

from . import create_app
from settings import DefaultConfig

app = create_app(DefaultConfig)


@app.route('/connect', methods=['GET'])
def first_connect():
    b = request.args

    try:
        check_signature(token='pekoandmiko35p', signature=b['signature'], timestamp=b['timestamp'],
                        nonce=b['nonce'])
        response = b['echostr']
    except InvalidSignatureException:
        response = '验证失败'
        return response, 401

    return response, 200


@app.route('/connect', methods=['POST'])
def on_post():
    xml = request.data
    msg = parse_message(xml)
    print(msg.type)
    if msg.type in app.config['HANDLE_TYPE']:
        xml = MessageHandler.getxml(msg)
        response = (xml)
    else:
        response = 'success'
    return response, 200















